//import 'package:amap_base_location/amap_base_location.dart';
import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:ui';
import 'dart:async';

import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/custom/LoadingPage.dart';
import 'package:flutter_juwo/ui/custom/MySeparator.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/custom/real_rich_text.dart';
import 'package:flutter_juwo/ui/model/home_data_entity.dart';
import 'package:flutter_juwo/ui/pages/homePages/serviceDialog.dart';
import 'package:flutter_juwo/ui/pages/homePages/top_banner.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:amap_location/amap_location.dart';

const APPBAR_SCROLL_OFFSET = 100;

// ignore: must_be_immutable
class Home extends StatefulWidget {
  Function(int) _function;

  Home(fun(value)) {
    this._function = fun;
  }

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  HomeDataEntity _homeDataEntity = null;
  MyPageState ps = MyPageState.LOADING;

  getBody(List<String> pics) {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }
    if (ps == MyPageState.HAVE_DATA) {
      return EasyRefresh(
          child: ListView(
        shrinkWrap: true,
        children: <Widget>[
          this.getTop(pics, _homeDataEntity.data.head.headtxt),
          this.getMiddle(),
          this.getService(
              _homeDataEntity.data.service.vxservice,
              _homeDataEntity.data.worktime.startTime,
              _homeDataEntity.data.worktime.endTime,
              _homeDataEntity.data.service.pic),
          this.getBottom(_homeDataEntity.data.content),
        ],
      ));
    }
    if (ps == MyPageState.NOT_DATA) {
      return NoData(getData);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    List<String> pics = [];
    if (_homeDataEntity != null) {
      for (int i = 0; i < _homeDataEntity.data.head.headpic.length; i++) {
        pics.add(_homeDataEntity.data.head.headpic[i].src);
      }
    }

    return Scaffold(
      backgroundColor: Colours.c243,
      appBar: myAppBar(context, "首页"),
      body: getBody(pics),
    );
  }

  @override
  void initState() {
    super.initState();

    PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    PermissionHandler().checkPermissionStatus(PermissionGroup.location);
    PermissionHandler().requestPermissions(<PermissionGroup>[
      PermissionGroup.storage, // 在这里添加需要的权限
      PermissionGroup.location, // 在这里添加需要的权限
    ]);

    //测试用户
    // SpUtil.putString(SpKeys.userToken, "gSAI-BvPdxYYRXhJ_nnpj7RpDYjyXzRf_1572599181");
    getLocation();

    ///获取数据
    this.getData();
    var widgetsBinding = WidgetsBinding.instance;
    widgetsBinding.addPostFrameCallback((callback) {
      ///会在Build完成时 回调 nice
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    AMapLocationClient.shutdown();
    super.dispose();
  }

  Widget myAppBar(BuildContext context, String title) {
    return new AppBar(
      backgroundColor: Colours.white,
      elevation: 0.0,
      brightness: Brightness.light,
      centerTitle: true,
      title: Text('$title',
          style: TextStyle(
              fontSize: ScreenUtil().setSp(34),
              fontFamily: Font.PingFangMedium,
              color: Colours.appC1)),
      actions: <Widget>[
        GestureDetector(
          onTap: () {
            Application.router.navigateTo(context, Routes.commonProblem);
          },
          child: Container(
            margin: EdgeInsets.only(right: ScreenUtil().setWidth(30)),
            child: Icon(
              Icons.help_outline,
              color: Colors.black,
              size: 24,
            ),
          ),
        )
      ],
    );
  }

  Future getData() async {
    DioManager.getInstance().get(Api.HOME, null, (json) {
      _homeDataEntity = HomeDataEntity.fromJson(json);
      if (null == _homeDataEntity) {
        return;
      }
      if (_homeDataEntity.code == Api.SUCCESS_CODE) {
        SpUtil.putString(
            SpKeys.serviceWx, _homeDataEntity.data.service.vxservice);
        SpUtil.putString(
            SpKeys.serviceStartTime, _homeDataEntity.data.worktime.startTime);
        SpUtil.putString(
            SpKeys.serviceEndTime, _homeDataEntity.data.worktime.endTime);
        SpUtil.putString(
            SpKeys.serviceQRCpode, _homeDataEntity.data.service.pic);
        ps = MyPageState.HAVE_DATA;
        setState(() {});
        return;
      }

      if (_homeDataEntity.code == Api.ERROR_CODE_0 ||
          _homeDataEntity.code == Api.ERROR_CODE) {
        ToastUtil.showShortErrToast(_homeDataEntity.message);
        return;
      }
    }, (errMsg) {
      ps = MyPageState.NOT_DATA;
      setState(() {});
      ToastUtil.showShortErrToast(errMsg.toString());
    }, isToken: false);
  }

  getTop(List<String> pics, String headtxt) {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6), color: Colors.white),
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10)),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(10),
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(10)),
            child: TopBanner(pics),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(0),
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(10)),
            child: Html(
              data: headtxt,
              blockSpacing: 0,
            ),
          )
        ],
      ),
    );
  }

  getMiddle() {
    List<Widget> widgets = [];
    widgets.add(this.getItem("icon_all", "全部"));
    widgets.add(this.getItem("icon_tb", "淘宝"));
    widgets.add(this.getItem("icon_jd", "京东"));
    widgets.add(this.getItem("icon_pdd", "拼多多"));
    widgets.add(this.getItem("icon_view", "浏览"));

    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6), color: Colors.white),
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10)),
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(0),
          ScreenUtil().setWidth(30), 0, ScreenUtil().setWidth(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: widgets,
      ),
    );
  }

  getBottom(String content) {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6), color: Colors.white),
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10)),
      child: Column(
        children: <Widget>[
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Icon(
                  Icons.security,
                  color: Colors.black,
                  size: 20,
                ),
                Container(
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(15)),
                  child: Text(
                    "注意事项",
                    style: TextStyles.custom(
                        32, Colours.appC1, Font.PingFangBlod),
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(0),
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(10)),
            child: Html(
              data: content,
              blockSpacing: 0,
            ),
          )
        ],
      ),
    );
  }

  getService(String wx, String startTime, String endTime, String imgUrl) {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6), color: Colors.white),
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(10)),
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(20),
                ScreenUtil().setWidth(10)),
            child: Row(
              children: <Widget>[
                Container(
                  child: Icon(
                    Icons.insert_emoticon,
                    color: Colors.black,
                    size: 24,
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                      margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                      child: RealRichText([
                        TextSpan(
                            text: "唯一官方客服微信：",
                            style: TextStyles.custom(30, Colours.appC1,
                                Font.PingFangRegular)),
                        TextSpan(
                            text: "${wx}",
                            style: TextStyles.custom(
                                32, Colours.appC11, Font.PingFangBlod),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                ClipboardData data =
                                    new ClipboardData(text: "${wx}");
                                Clipboard.setData(data);
                                ToastUtil.showShortToast("已复制");
                              })
                      ])),
                ),
                GestureDetector(
                  onTap: () {
                    ///显示dialog
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (BuildContext context) {
                          return ServiceDialog(startTime, endTime, wx, imgUrl);
                        });
                  },
                  child: Container(
                    child: Icon(
                      Icons.wallpaper, //wallpaper  filter_center_focus
                      color: Colors.black,
                      size: 20,
                    ),
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: ScreenUtil().setWidth(78)),
            alignment: Alignment.centerLeft,
            child: RealRichText([
              TextSpan(
                  text: "有问题先看",
                  style: TextStyles.custom(
                      26, Colours.appC2, Font.PingFangRegular)),
              TextSpan(
                  text: "【常见问题】",
                  style: TextStyles.custom(
                      28, Colours.appC11, Font.PingFangMedium),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Application.router
                          .navigateTo(context, Routes.commonProblem);
                    }),
              TextSpan(
                  text: "找不到答案再问客服",
                  style: TextStyles.custom(
                      26, Colours.appC2, Font.PingFangRegular)),
            ]),
          ),
          Container(
            margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
            child: MySeparator(
              color: Colours.appC7,
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30), 0,
                ScreenUtil().setWidth(20), ScreenUtil().setWidth(20)),
            child: Row(
              children: <Widget>[
                Container(
                  child: Icon(
                    Icons.access_time,
                    color: Colours.appC3,
                    size: 16,
                  ),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(16)),
                  child: Text(
                    "客服工作时间：$startTime-$endTime",
                    style: TextStyles.custom(
                        26, Colours.appC3, Font.PingFangRegular),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  ///任务类型item
  Widget getItem(String imgName, String type) {
    return Container(
      child: GestureDetector(
        onTap: () {
          if (type == "全部") {
            widget._function(0);
            return;
          } else if (type == "淘宝") {
            widget._function(1);
            return;
          } else if (type == "京东") {
            widget._function(2);
            return;
          } else if (type == "拼多多") {
            widget._function(3);
            return;
          } else if (type == "浏览") {
            widget._function(4);
            return;
          }
        },
        child: Column(
          children: <Widget>[
            Container(
              child: Image.asset(
                Utils.getImgPath(imgName),
                width: ScreenUtil().setWidth(90),
                height: ScreenUtil().setWidth(90),
              ),
            ),
            Container(
                child: Text("$type",
                    style: TextStyles.custom(
                        30, Colours.appC2, Font.PingFangMedium))),
          ],
        ),
      ),
    );
  }

  void getLocation() async {
    await AMapLocationClient.startup(new AMapLocationOption(
        desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters));
    AMapLocation location = await AMapLocationClient.getLocation(true);
    FormData formData = FormData.from(
        {"longitude": location.longitude, "dimension": location.latitude});
    DioManager.getInstance()
        .post(Api.USER_ADDLOCATION, formData, (json) {}, (err) {});
    AMapLocationClient.stopLocation();
  }
}
